package com.easylinkin.linkappapi.circuit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.circuit.dto.*;
import com.easylinkin.linkappapi.circuit.entity.RailGiveAlarmTypeConfig;
import com.easylinkin.linkappapi.circuit.entity.RailGiveSystemAlarm;
import com.easylinkin.linkappapi.circuit.mapper.RailGiveAlarmTypeConfigMapper;
import com.easylinkin.linkappapi.circuit.mapper.RailGiveSystemAlarmMapper;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.circuit.vo.RailGiveSystemAlarmVO;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.message.SendMessageUtil;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.mechanical.service.IMechanicalService;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 系统告警记录服务类
 * @author lyk
 * @date 2025/6/17 下午 2:31
 */
@Service
@Slf4j
public class RailGiveSystemAlarmServiceImpl  extends ServiceImpl<RailGiveSystemAlarmMapper, RailGiveSystemAlarm>  implements IRailGiveSystemAlarmService {
    @Resource
    private CommonService commonService;
    @Autowired
    private RailGiveAlarmTypeConfigMapper giveAlarmTypeConfigMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private SendMessageUtil sendMessageUtil;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private IMechanicalService mechanicalService;

    /**
     * 告警短信推送模板
     */
    private static final String SMS_ALARM_CODE_REMINDER_PROCESSING = "SMS_490090449";
    /**
     * 处理系统告警 [用电]
     * @param datapushDTO
     */
    @Override
    public void datapushHandlerUseEle(DatapushDTO datapushDTO, SysDictItem dictItem, RailGiveAlarmTypeConfigEnum giveAlarmTypeConfigEnum) {
        if (Objects.isNull(dictItem)){
            return;
        }
        if (Objects.isNull(giveAlarmTypeConfigEnum)){
            return;
        }
        JSONObject data = datapushDTO.getData();
        if (Objects.isNull(data)){
            return;
        }
        Device device = datapushDTO.getDevice_data_latest();
        if (Objects.isNull(device)){
            return;
        }
        //查询配置
        QueryWrapper<RailGiveAlarmTypeConfig> objectQueryWrapper = new QueryWrapper<RailGiveAlarmTypeConfig>();
        objectQueryWrapper.eq("type",giveAlarmTypeConfigEnum.getType());
        //查询启用
        objectQueryWrapper.eq("enabled",0);
        objectQueryWrapper.eq("tenant_id",device.getTenantId());
        RailGiveAlarmTypeConfig railGiveAlarmTypeConfig = giveAlarmTypeConfigMapper.selectOne(objectQueryWrapper);
        if (Objects.isNull(railGiveAlarmTypeConfig)){
            return;
        }
        String textmsg = "";
        RailGiveSystemAlarm nowAlarm = new RailGiveSystemAlarm();
        nowAlarm.setDeviceCode(device.getCode());
        nowAlarm.setCreateTime(new Date());
        nowAlarm.setTestingItem(dictItem.getItemValue());
        nowAlarm.setAlarmType(railGiveAlarmTypeConfig.getType());
        nowAlarm.setLevel(railGiveAlarmTypeConfig.getLevel());
        nowAlarm.setTenantId(device.getTenantId());
        switch (giveAlarmTypeConfigEnum){
            case AlarmType_1:
                //剩余电流过高告警
                if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getFieids())){
                    String[] split = railGiveAlarmTypeConfig.getFieids().split(",");
                    for (String fd:split){
                        Double aDouble = Objects.isNull(data.getDouble(fd))?0.00:data.getDouble(fd);
                        if (aDouble>=railGiveAlarmTypeConfig.getThreshValue()){
                           //生成告警
                            nowAlarm.setStatus(0);
                            nowAlarm.setContent("当前剩余电流"+aDouble+"，请注意");
                            textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                                    , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                            nowAlarm.setPushContent(textmsg);
                            break;
                        }
                    }
                }
                break;
            case AlarmType_2:
                //温度过高告警
                if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getFieids())){
                    String[] split = railGiveAlarmTypeConfig.getFieids().split(",");
                    for (String fd:split){
                        Double aDouble = Objects.isNull(data.getDouble(fd))?0.00:data.getDouble(fd);
                        if (aDouble>=railGiveAlarmTypeConfig.getThreshValue()){
                            nowAlarm.setStatus(0);
                            nowAlarm.setContent("温度报警、温度:"+aDouble+"。");
                            textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                                    , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                            nowAlarm.setPushContent(textmsg);
                            break;
                        }
                    }
                }
                break;
            case AlarmType_3:
                //供电中断告警
                if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getFieids())){
                    String[] split = railGiveAlarmTypeConfig.getFieids().split(",");
                    for (String fd:split){
                        Integer aInt = Objects.isNull(data.getInteger(fd))?0:data.getInteger(fd);
                        if (aInt.intValue() == railGiveAlarmTypeConfig.getThreshValue().intValue()){
                            nowAlarm.setStatus(0);
                            nowAlarm.setContent("当前设备供电中断");
                            textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                                    , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                            nowAlarm.setPushContent(textmsg);
                            break;
                        }
                    }
                }
                break;
            case AlarmType_4:
                //压/电流逆向序告警
                if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getFieids())){
                    String[] split = railGiveAlarmTypeConfig.getFieids().split(",");
                    Integer voltage_reverse = 0;
                    Integer current_reverse = 0;
                    for (String fd:split){
                        Integer aInt = Objects.isNull(data.getInteger(fd))?0:data.getInteger(fd);
                        if (aInt.intValue() == railGiveAlarmTypeConfig.getThreshValue().intValue()){
                            if (fd.equals("voltage_reverse")){
                                //电压逆向
                                voltage_reverse = aInt;
                            }else if (fd.equals("current_reverse")){
                                //电流逆向
                                current_reverse = aInt;
                            }
                        }
                    }
                    List<String> vc_array = new ArrayList<>();
                    if (voltage_reverse.equals(1)){
                        vc_array.add("电压");
                    }
                    if (current_reverse.equals(1)){
                        vc_array.add("电流");
                    }
                    if (vc_array.size()>0){
                        String join = String.join(",", vc_array);
                        nowAlarm.setStatus(0);
                        nowAlarm.setContent("当前设备"+join+"逆向序报警");
                        textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                                , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                        nowAlarm.setPushContent(textmsg);
                        break;
                    }
                }
                break;
            case AlarmType_5:
                //A/B/C相告警
                if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getFieids())){
                    String[] split = railGiveAlarmTypeConfig.getFieids().split(",");
                    Map<String, Integer> objectObjectHashMap = new HashMap<>();
                    List<String> vc_array = new ArrayList<>();
                    for (String fd:split){
                        Integer aInt = Objects.isNull(data.getInteger(fd))?0:data.getInteger(fd);
                        if (aInt.intValue() == railGiveAlarmTypeConfig.getThreshValue().intValue()){
                            String s = AlarmPushTemplate.each_other.get(fd);
                            if (!StringUtils.isEmpty(s)){
                                vc_array.add(s);
                            }
                        }
                    }
                    if (vc_array.size()>0){
                        String join = String.join(",", vc_array);
                        nowAlarm.setStatus(0);
                        nowAlarm.setContent(join);
                        textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                                , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                        nowAlarm.setPushContent(textmsg);
                        break;
                    }
                }
                break;
            case AlarmType_6:
                //断路器故障
                //告警内容为：触发对应的告警时，设备给的所有故障代码中的故障类型；例如当有断路器故障时，
                //设备流水中给的故障代码中的类型同时有过压、电弧故障时；则告警内容就是过压、电弧故障
                String fault_code = data.getString("fault_code");
                FaultCodeTypeEnum fault = FaultCodeTypeEnum.getEnumByCode(fault_code);
                GiveCodeTypeEnum  give  = GiveCodeTypeEnum.getEnumByCode(fault_code);
                String join = "";
                if (!Objects.isNull(fault)){
                    join = fault.getName();

                }
                if (!Objects.isNull(give)){
                    join = give.getName();
                }
                if (!StringUtils.isEmpty(join)){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent(join);
                    textmsg = getElectricalSafetyPushContent(DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), railGiveAlarmTypeConfig.getText()
                            , DateUtil.getYYYYMMDDHHMMSSDate(nowAlarm.getCreateTime()), StringUtils.isEmpty(device.getName()) ? device.getCode() : device.getName(), nowAlarm.getContent());
                    nowAlarm.setPushContent(textmsg);
                    break;
                }
                break;

        }
        if (Objects.isNull(nowAlarm.getStatus())){
            return;
        }
        nowAlarm.setCategory(railGiveAlarmTypeConfig.getCategory());
        //保存告警记录
        baseMapper.insert(nowAlarm);
        //判断是否发送短信
        if (!Objects.isNull(railGiveAlarmTypeConfig.getPushMeth())){
            if (!railGiveAlarmTypeConfig.getPushMeth().contains("2")){
                return;
            }
            //发送短信通知
            if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getPushUserPhones())){
                String[] phones = railGiveAlarmTypeConfig.getPushUserPhones().split(",");
                for (String phoneNumber:phones){
                    if (!StringUtils.isEmpty(phoneNumber)){
                        if (!StringUtils.isEmpty(nowAlarm.getPushContent())){
                            sendMessageUtil.sendSms(phoneNumber,SMS_ALARM_CODE_REMINDER_PROCESSING,nowAlarm.getPushContent());
                        }
                    }else{
                        continue;
                    }

                }

            }
        }
    }

    /**
     * 处理系统告警 [AI安防]
     * @param datapushDTO
     * @param dictItem
     * @param giveAlarmTypeConfigEnum
     */
    @Override
    public void datapushHandlerAiData(DatapushDTO datapushDTO, SysDictItem dictItem, RailGiveAlarmTypeConfigEnum giveAlarmTypeConfigEnum){
        if (Objects.isNull(dictItem)){
            return;
        }
        if (Objects.isNull(giveAlarmTypeConfigEnum)){
            return;
        }
        JSONObject data = datapushDTO.getData();
        if (Objects.isNull(data)){
            return;
        }
        Device device = datapushDTO.getDevice_data_latest();
        if (Objects.isNull(device)){
            return;
        }
        //查询配置
        QueryWrapper<RailGiveAlarmTypeConfig> objectQueryWrapper = new QueryWrapper<RailGiveAlarmTypeConfig>();
        objectQueryWrapper.eq("type",giveAlarmTypeConfigEnum.getType());
        //查询启用
        objectQueryWrapper.eq("enabled",0);
        objectQueryWrapper.eq("tenant_id",device.getTenantId());
        RailGiveAlarmTypeConfig railGiveAlarmTypeConfig = giveAlarmTypeConfigMapper.selectOne(objectQueryWrapper);
        if (Objects.isNull(railGiveAlarmTypeConfig)){
            return;
        }
        String textmsg = "";
        RailGiveSystemAlarm nowAlarm = new RailGiveSystemAlarm();
        nowAlarm.setDeviceCode(device.getCode());
        nowAlarm.setCreateTime(new Date());
        nowAlarm.setTestingItem(dictItem.getItemValue());
        nowAlarm.setAlarmType(railGiveAlarmTypeConfig.getType());
        nowAlarm.setLevel(railGiveAlarmTypeConfig.getLevel());
        nowAlarm.setTenantId(device.getTenantId());
        switch (giveAlarmTypeConfigEnum){
            case AlarmType_24:
                //跌倒
                String values = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(values))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_25:
                //烟火，（有可能是烟，也可能是火）06 - 明火，/07 - 烟雾
                String  ywmh = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (Double.valueOf(6).equals(Double.valueOf(ywmh)) || Double.valueOf(7).equals(Double.valueOf(ywmh))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_26:
                // 举手求救
                String  qsqj = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(qsqj))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_27:
                // 外来人员入侵  暂无
                break;
            case AlarmType_28:
                // 区域入侵 03
                String  qyrq = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(qyrq)) ){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_29:
                //未穿反光衣 05
                String wcfgy = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(wcfgy))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_30:
                //未系安全带  -10 -11
                String  wxaqd = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (Double.valueOf(10).equals(Double.valueOf(wxaqd)) || Double.valueOf(11).equals(Double.valueOf(wxaqd))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_31:
                //未带安全帽 00s
                String wdaqm = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(wdaqm))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_32:
                //吸烟 00
                String xy = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(xy))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            case AlarmType_33:
                //打架 08
                String dj = data.getString(railGiveAlarmTypeConfig.getFieids());
                if (railGiveAlarmTypeConfig.getThreshValue().equals(Double.valueOf(dj))){
                    nowAlarm.setStatus(0);
                    nowAlarm.setContent("当前有人["+giveAlarmTypeConfigEnum.getText()+"],["+DateUtil.getYYYYMMDDHHMMSSDate(new Date())+"]");
                }
                break;
            default:
                break;
        }

        if (Objects.isNull(nowAlarm.getStatus())){
            return;
        }
        nowAlarm.setCategory(railGiveAlarmTypeConfig.getCategory());
        //保存告警记录
        baseMapper.insert(nowAlarm);
        //更新设备告警
        deviceMapper.updateStatusById(device.getId(),1);
        //判断是否发送短信
        if (!Objects.isNull(railGiveAlarmTypeConfig.getPushMeth())){
            if (!railGiveAlarmTypeConfig.getPushMeth().contains("2")){
                return;
            }
            //发送短信通知
            if (!StringUtils.isEmpty(railGiveAlarmTypeConfig.getPushUserPhones())){
                String[] phones = railGiveAlarmTypeConfig.getPushUserPhones().split(",");
                for (String phoneNumber:phones){
                    if (!StringUtils.isEmpty(phoneNumber)){
                        if (!StringUtils.isEmpty(nowAlarm.getPushContent())){
                            sendMessageUtil.sendSms(phoneNumber,SMS_ALARM_CODE_REMINDER_PROCESSING,nowAlarm.getPushContent());
                        }
                    }else{
                        continue;
                    }

                }

            }
        }
    }


    /**
     *
     * @param page
     * @param customQueryParams
     * @return
     */
    @Override
    public IPage<RailGiveSystemAlarmVO> selectPage(Page page, RailGiveSystemAlarmDTO customQueryParams) {
        customQueryParams.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        IPage<RailGiveSystemAlarmVO> page1 = baseMapper.findPage(page, customQueryParams);
        page1.getRecords().stream().forEach(item -> {
            RailGiveAlarmTypeConfigEnum anEnum = RailGiveAlarmTypeConfigEnum.getEnum(item.getAlarmType());
            if (Objects.nonNull(anEnum)){
                item.setAlarmTypeText(anEnum.getText());
                item.setBigScreenAlarmContent(buildBigScreenAlarmContent(item));
            }
        });
        return page1;
    }

    private String buildBigScreenAlarmContent(RailGiveSystemAlarmVO item) {
        String bigScreenAlarmContent = "";
        // 处理大屏告警内容
        // 大类id 1-吊车安全监测 2-防护员电子围栏 3-用电安全 4-汛情防护  5-AI行为告警 6-现场广播 7-网格员电子围栏
        switch (item.getCategory()){
            case "1":
                //吊车安全监测
                if (item.getAlarmType().equals(RailGiveAlarmTypeConfigEnum.AlarmType_7.getType())){
                    bigScreenAlarmContent = item.getDeviceName() + "," + item.getContent();
                } else {
                    bigScreenAlarmContent = item.getTestingItem() + "," + item.getContent();
                }
                break;
            case "2":
                //防护员电子围栏
                bigScreenAlarmContent = item.getContent();
                break;
            case "3":
                //用电安全
                bigScreenAlarmContent = item.getDeviceName() + "," + item.getContent();
                break;
            case "4":
                //汛情防护
                bigScreenAlarmContent = item.getContent();
                break;
            case "5":
                //AI行为告警
                bigScreenAlarmContent = item.getContent();
                break;
            case "6":
                //现场广播
                bigScreenAlarmContent = item.getContent();
                break;
            case "7":
                //网格员电子围栏
                break;
            default:
                bigScreenAlarmContent = item.getContent();
                break;
        }
        return bigScreenAlarmContent;
    }

    @Override
    public Map<String, Object> totalOldDayByLevelPieChart(String category) {
        Map<String, Object> result = new HashMap<>();
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        String oldDay = DateUtil.getLastDays(1);
        int sum = baseMapper.amountByOneTenantId(tenantId, category);
        //未处理总数
        int unHandleSum = baseMapper.amountByOneTenantIdAndStatus(tenantId, category, 0);
        //已处理总数
        int handleSum = sum - unHandleSum;
        //昨天数量
        int oldSum = baseMapper.amountByOneDate(tenantId, oldDay, category);
        //今天数量
        String dayDate = DateUtil.getYYYYMMDDDate(new Date());
        int nowSum = baseMapper.amountByOneDate(tenantId,dayDate, category);
        //近一个月的数量
        String startDate = DateUtil.getLastDays(29);
        int intervalThirtySum =  baseMapper.amountByOneDateInterval(tenantId,startDate,dayDate, category);
        //比昨日增长数量 正数或者负数
        int growthSum = 0;
        if (nowSum>oldSum){
            growthSum = nowSum-oldSum;
        }else if (nowSum<oldSum){
            growthSum = Integer.valueOf(0) - (oldSum-nowSum);
        }else{
            growthSum = 0;
        }
        List<Map<String,Object>> levelResList = new ArrayList<>();
        String[] levels = new String[]{"1","2","3"};
        String[] levels_view = new String[]{"I级","II级","III级"};
        List<String> levelArray = Arrays.asList(levels);
        for (int index=0;index<levelArray.size();index++){
            int i = baseMapper.amountByOneLevel(tenantId, levelArray.get(index), category);
            Map<String, Object> map = new HashMap<>();
            map.put("level",levelArray.get(index));
            map.put("levelText",levels_view[index]);
            map.put("sum",i);
            levelResList.add(map);
        }
        result.put("sum",sum);
        result.put("unHandleSum",unHandleSum);
        result.put("handleSum",handleSum);
        result.put("oldSum",oldSum);
        result.put("nowSum",nowSum);
        result.put("growthSum",growthSum);
        result.put("levelResList",levelResList);
        //最近30天的告警
        result.put("intervalThirtySum",intervalThirtySum);
        return result;
    }

    @Override
    public Map<String, Object> daysWeekMonthlyByLineChart(RailGiveSystemAlarmDTO dto) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        String category = dto.getCategory();
        List<String> dates = null;
        switch (dto.getLineDateType()){
            case 0:
                //今日
                dates = DateUtil.getHoursFrom1AM();
                dto.setStartDateH(dates.get(0));
                dto.setEndDateH(dates.get(dates.size()-1));
                break;
            case 1:
                //近1周
                dates = DateUtil.getLastByListDays(7);
                dto.setStartDate(dates.get(0));
                dto.setEndDate(dates.get(dates.size()-1));
                break;
            case 2:
                //30天
                dates = DateUtil.getLastByListDays(30);
                dto.setStartDate(dates.get(0));
                dto.setEndDate(dates.get(dates.size()-1));
                break;
            default:
                break;
        }
        if (Objects.isNull(dates)){
            return new HashMap<>();
        }
        dto.setTenantId(tenantId);
        dto.setCategory(category);
        List<RailGiveSystemAlarmVO> railGiveSystemAlarmVOS = baseMapper.findPage(dto);
        //遍历
        List<RailGiveSystemAlarmVO> transferStation = new ArrayList<>();
        boolean zero = false;
        List<String> abscissa = new ArrayList<>();
        List<Integer> sums = new ArrayList<>();
        for(String data:dates){
            int sum = 0;
            if (dto.getLineDateType().equals(0)){
                abscissa.add(DateUtil.convertToHourFormat(data));
            }else{
                abscissa.add(data);
            }
            if (zero) {
                sums.add(sum);
                continue;
            }
            if (transferStation.size() == 0 ){
                int leftIndex = 0;
                int rightIndex  = railGiveSystemAlarmVOS.size()-1;
                while (leftIndex<=rightIndex){
                   if (leftIndex == rightIndex){
                       RailGiveSystemAlarmVO leftAlarmVO = railGiveSystemAlarmVOS.get(leftIndex);
                       String leftCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(leftAlarmVO.getCreateTime());
                       if (leftCreateTime.startsWith(data)){
                           sum++;
                       }else{
                           transferStation.add(leftAlarmVO);
                       }
                       break;
                   }
                   RailGiveSystemAlarmVO leftAlarmVO = railGiveSystemAlarmVOS.get(leftIndex);
                   String leftCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(leftAlarmVO.getCreateTime());
                   if (leftCreateTime.startsWith(data)){
                        sum++;
                   }else{
                        transferStation.add(leftAlarmVO);
                   }
                   leftIndex++;
                    RailGiveSystemAlarmVO rightAlarmVO  = railGiveSystemAlarmVOS.get(rightIndex);
                    String rightCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(rightAlarmVO.getCreateTime());
                    if (rightCreateTime.startsWith(data)){
                        sum++;
                    }else{
                        transferStation.add(rightAlarmVO);
                    }
                    rightIndex--;
                }
            }else{
                List<RailGiveSystemAlarmVO> letw = transferStation;
                transferStation = new ArrayList<>();
                int leftIndex = 0;
                int rightIndex  = letw.size()-1;
                while (leftIndex<=rightIndex) {
                    if (leftIndex == rightIndex){
                        RailGiveSystemAlarmVO leftAlarmVO = letw.get(leftIndex);
                        String leftCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(leftAlarmVO.getCreateTime());
                        if (leftCreateTime.startsWith(data)){
                            sum++;
                        }else{
                            transferStation.add(leftAlarmVO);
                        }
                        break;
                    }
                    RailGiveSystemAlarmVO leftAlarmVO = letw.get(leftIndex);
                    String leftCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(leftAlarmVO.getCreateTime());
                    if (leftCreateTime.startsWith(data)){
                        sum++;
                    }else{
                        transferStation.add(leftAlarmVO);
                    }
                    leftIndex++;
                    RailGiveSystemAlarmVO rightAlarmVO  = letw.get(rightIndex);
                    String rightCreateTime = DateUtil.getYYYYMMDDHHMMSSDate(rightAlarmVO.getCreateTime());
                    if (rightCreateTime.startsWith(data)){
                        sum++;
                    }else{
                        transferStation.add(rightAlarmVO);
                    }
                    rightIndex--;
                }
            }
            if (transferStation.size() == 0) {
                zero = true;
            }
            sums.add(sum);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("abscissa",abscissa);
        result.put("sums",sums);
        return result;
    }


    @Override
    public List<AlarmTypeCount> alarmTypeCount(String category, List<String> typeList, Date startTime, Date endTime) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        List<AlarmTypeCount> alarmTypeCounts = baseMapper.alarmTypeCount(tenantId, category, typeList,startTime,endTime);
        if (CollectionUtils.isNotEmpty(alarmTypeCounts)) {
            for (AlarmTypeCount alarmTypeCount : alarmTypeCounts) {
                RailGiveAlarmTypeConfigEnum anEnum = RailGiveAlarmTypeConfigEnum.getEnum(alarmTypeCount.getAlarmType());
                if (Objects.nonNull(anEnum)){
                    alarmTypeCount.setName(anEnum.getText());
                }
            }
        }
        return alarmTypeCounts;
    }

    @Override
    public void handle(RailGiveSystemAlarmDTO dto) {
        RailGiveSystemAlarm railGiveSystemAlarm = baseMapper.selectById(dto.getId());
        if (Objects.isNull(railGiveSystemAlarm)){
            return;
        }
        LinkappUser notNullCurrent = linkappUserContextProducer.getNotNullCurrent();
        railGiveSystemAlarm.setHandleName(notNullCurrent.getNickname());
        railGiveSystemAlarm.setHandleId(String.valueOf(notNullCurrent.getId()));
        railGiveSystemAlarm.setHandleRest(dto.getHandleRest());
        //状态改变
        railGiveSystemAlarm.setStatus(dto.getHandleRest().equals(0)?1:dto.getHandleRest().equals(1)?2:null);
        if (!StringUtils.isEmpty(dto.getHandleFileUrls())){
            railGiveSystemAlarm.setHandleFileUrls(dto.getHandleFileUrls());
        }
        if (!StringUtils.isEmpty(dto.getHandleResp())){
            railGiveSystemAlarm.setHandleResp(dto.getHandleResp());
        }
        commonService.setModifyInfo(railGiveSystemAlarm);
        baseMapper.updateById(railGiveSystemAlarm);
    }

    @Override
    public Map<String, Object> getHandleInfo(String id) {
        RailGiveSystemAlarm railGiveSystemAlarm = baseMapper.selectById(Long.valueOf(id));
        if (Objects.isNull(railGiveSystemAlarm)){
            return null;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("handleRest",railGiveSystemAlarm.getHandleRest());
        result.put("handleResp",railGiveSystemAlarm.getHandleResp());
        result.put("handleFileUrls",railGiveSystemAlarm.getHandleFileUrls());
        return result;
    }

    @Override
    public List<RailGiveSystemAlarmVO> todayEleEquipmentAlarmList() {
        RailGiveSystemAlarmDTO dto =  new RailGiveSystemAlarmDTO();
        List<String> dates = DateUtil.getHoursFrom1AM();
        dto.setStartDateH(dates.get(0));
        dto.setEndDateH(dates.get(dates.size()-1));
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        dto.setTenantId(tenantId);
        dto.setCategory(RailGiveAlarmTypeConfigEnum.AlarmType_1.getCategory());
        List<RailGiveSystemAlarmVO> listByCondition = baseMapper.findPage(dto);
        return listByCondition;
    }


    /**
     * 用电安全短信消息推送内容拼接
     */
    public String getElectricalSafetyPushContent(String datetime,String...ps){
         String dqhzPushMsg = AlarmPushTemplate.DQHZ_PUSH_MSG;
         for (int i=0;i<ps.length;i++){
             dqhzPushMsg = dqhzPushMsg.replace("#" + i, ps[i]);
         }
        return dqhzPushMsg.replace("#{datetime}", datetime);
    }

}
